<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/9/23 20:36
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

class Purchaser extends ADM_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function comp()
    {
        $send['state'] = false;
        do {

            $id = $this->input->get('id');
            if (empty($id)) {
                $send['error'] = '参数错误';
                break;
            }

            $db = clone ($this->db);
            $q = $db->get_where('base_bill_apply', ['id' => $id]);
            $row = $q->row_array();
            if (empty($row)) {
                $send['error'] = '无此对账单';
                break;
            }

            if ($row['status'] == 6) {
                $send['error'] = '状态错误';
                break;
            }

            $db2 = clone ($this->db);
            $db2->where('id', $id);
            $db2->update('base_bill_apply', ['status' => 6]);
            if ($db2->affected_rows()) {
                $send['state'] = true;
            } else {
                $send['error'] = '设置失败';
            }
        } while(false);

        $this->output->send($send);
    }

    public function index()
    {
        $q = $this->db
            ->select('b.name as baseName, a.*')
            ->join('base as b', 'b.id=a.baseId')
            ->where('a.status', 0)
            ->get('base_bill_apply as a');
        $rows = $q->result_array();

        if (!empty($rows)) foreach ($rows as &$row) {
            $row['total'] = money_format('%i', $row['total'] / 100);
            $row['refund'] = money_format('%i', $row['refund'] / 100);
            $row['delivery'] = money_format('%i', $row['delivery'] / 100);
            $row['left'] = money_format('%i', $row['left'] / 100);
            $row['fx'] = money_format('%i', $row['fx'] / 100);
        }

        $this->load->view('admin/bill/apply.html', [
            'data' => $rows
        ]);
    }

    public function detail()
    {
        $id = $this->input->get('id');
        if (empty($id)) {
            echo 'page error';
            die;
        }

        $item = $this->getItem($id);
        if (empty($item)) {
            echo 'invalid request';
            die;
        }

        $data = $this->getData(['year' => $item['year'], 'month' => $item['month'], 'baseId' => $item['baseId']]);
        $this->load->view('admin/bill/detail.html', [
            'base' => $this->getBaseInfo($item['baseId']),
            'info' => $item,
            'data' => $data
        ]);
    }

    public function export()
    {
        $id = $this->input->get('id');
        $year = $this->input->get('year');
        $month = $this->input->get('month');
        if (empty($id)) {
            if (empty($year) && empty($month)) {
                echo 'page error';
                die;
            }
            $params = [
                'year' => $year,
                'month' => $month,
                'baseId' => $this->baseId
            ];
        } else {
            $item = $this->getItem($id);
            if (empty($item)) {
                echo 'page error';
                die;
            }
            $params = [
                'year' => $item['year'],
                'month' => $item['month'],
                'baseId' => $this->baseId
            ];
        }


        $baseInfo = $this->getBaseInfo($this->baseId);
        $data = $this->getData($params);
        if (empty($data['lists'])) {
            echo 'page error';
            die;
        }

        $dataResult = array();
        foreach($data['lists'] as $val) {
            $dataResult[] = [
                $val['id'],
                $baseInfo['name'],
                $val['sn'],
                money_format('%i', $val['totalPrice'] / 100),
                money_format('%i', $val['goodsPrice'] / 100),
                money_format('%i', $val['expressPrice'] / 100),
                $val['payMode'] == 'online' ? '在线支付' : '货到付款',
                $val['payWay'] == 1 ? '支付宝' : '微信',
                $val['priceType'] == 1 ? "采购商" : '普通会员',
                $val['status'] == 'Complete' ? '已经完成' : '已退款',
                $val['compTime']
            ];
        }

        $headTitle = $baseInfo['name'] . ' ' . $params['year'] . '年' . $params['month'] . '交易账单';
        $title = $baseInfo['name'];
        // $headtitle= "<tr style='height:50px;border-style:none;><th border=\"0\" style='height:60px;width:270px;font-size:22px;' colspan='11' >{$headTitle}</th></tr>";
        $headtitle = $headTitle;
        $titlename = "<tr>
               <th style='width:70px;' >编号</th>
               <th style='width:150px;'>基地名称</th>
               <th style='width:100px;'>订单号</th>
               <th style='width:70px;'>交易金额</th>
               <th style='width:70px;'>商品金额</th>
               <th style='width:70px;'>物流费用</th>
               <th style='width:70px;'>支付类型</th>
               <th style='width:70px;'>支付方式</th>
               <th style='width:70px;'>订单类型</th>
               <th style='width:70px;'>订单状态</th>
               <th style='width:90px;'>完成时间</th>
           </tr>";
        $filename = $title.".xls";
        $this->excel($dataResult,$titlename,$headtitle,$filename);
    }

    public function excel($datas,$titlename,$title,$filename){
        $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>";
        $str .="<table border=1><caption>".$title."</caption>";
        $str .= $titlename;
        foreach ($datas  as $key=> $rt )
        {
            $str .= "<tr>";
            foreach ( $rt as $k => $v )
            {
                $str .= "<td>{$v}</td>";
            }
            $str .= "</tr>\n";
        }
        $str .= "</table></body></html>";
        header( "Content-Type: application/vnd.ms-excel; name='excel'" );
        header( "Content-type: application/octet-stream" );
        header( "Content-Disposition: attachment; filename=".$filename );
        header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
        header( "Pragma: no-cache" );
        header( "Expires: 0" );
        exit( $str );
    }

    /**
     * 基地数据
     * @param int $baseId
     * @return mixed
     */
    public function getBaseInfo($baseId = 0)
    {
        $db = clone($this->db);
        $q = $db->get_where('base', ['id' => $baseId]);
        return $q->row_array();
    }

    /**
     * @param $id
     * @return mixed
     */
    public function getItem($id)
    {
        $db = clone($this->db);
        $q = $db->get_where('base_bill_apply', ['id' => $id]);
        $row = $q->row_array();
        return $row;
    }

    /**
     * @param $params
     * @return array
     */
    public function getData($params)
    {
        $data = [
            'count' => 0,
            'total' => money_format('%i', 0),
            'refund' => money_format('%i', 0),
            'amount' => money_format('%i', 0),
            'delivery' => money_format('%i', 0),
            'lists' => []
        ];

        $this->load->model('common/Order_Model', 'o');
        $res = $this->o->checkOrder($params['year'], $params['month'], $params['baseId']);

        $totalPrice = 0;
        $refundPrice = 0;
        $delivery = 0;
        if (!empty($res)) foreach ($res as &$item) {
            $totalPrice += intval($item['totalPrice']);
            if ($item['status'] == 'Refunded') {
                $refundPrice += intval($item['goodsPrice']);
            }
            if ($item['payMode'] == 'delivery') {
                $delivery += intval($item['totalPrice']);
            }
            $item['totalPrice'] = money_format('%i', $item['totalPrice'] / 100);
        }

        $data['lists'] = $res;
        $data['count'] = !empty($res) ? count($res) : 0;
        $data['total'] = money_format('%i', $totalPrice / 100);
        $data['refund'] = money_format('%i', $refundPrice / 100);
        $data['amount'] = money_format('%i', ($totalPrice - $refundPrice - $delivery) / 100);

        return $data;
    }
}
